<template>
  <!-- 添加或修改服务对话框 -->
  <el-dialog :title="title" :visible.sync="visible" width="990px" append-to-body :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="服务中文名" prop="serviceCnName">
            <el-input v-model="form.serviceCnName" @change="handleDraft" placeholder="中文名,如:用户管理服务" maxlength="40" show-word-limit
                      style="width: 340px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务英文名" prop="serviceZnName">
            <el-input v-model="form.serviceZnName" @change="handleDraft"
                      placeholder="与服务中的spring.application.name属性一致" maxlength="40" show-word-limit
                      style="width: 340px;"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属分组" prop="groupId">
            <el-select v-model="form.groupId" @change="handleDraft" clearable filterable placeholder="分组是为了方便团队维护服务告警配置"
                       style="width: 340px;">
              <el-option v-for="group in groupOptions" :key="group.id" :label="group.groupName"
                         :value="group.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="chargeUserId">
            <template #label>
              <span class="custom-label">
                <span style="color: red;">*</span>
                负责人
              </span>
            </template>
            <el-select v-model="form.chargeUserId" @change="handleDraft" filterable clearable placeholder="该服务的负责人"
                       style="width: 340px;">
              <el-option v-for="user in userOptions" :key="user.userId" :label="user.name"
                         :value="user.userId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="降噪规则">
            <el-tooltip content="用于控制告警推送,当在周期(分钟)内同一个异常的告警的次数大于阈值时,则在静默时间(分钟)段内不再告警推送" placement="top">
              <i class="el-icon-question" style="color: #E6A23C; cursor: pointer;"></i>
            </el-tooltip>
            <span>
              周期
            </span>
            <el-input v-model="form.denoisePeriod" type="number" min="0" @change="handleDenoisePeriod"
                      style="width: 70px;"/>
            <span>
              阈值
            </span>
            <el-input v-model="form.denoiseCount" type="number" style="width: 70px;"/>
            <span>
              静默
            </span>
            <el-input v-model="form.denoiseSilencePeriod" type="number" style="width: 70px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="upgradesCount">
            <template #label>
              <el-tooltip content="当一个异常发生告警的次数超过该阈值时,将对异常的[频度等级]进行升级" placement="top">
                <i class="el-icon-question" style="color: #E6A23C; cursor: pointer;"></i>
              </el-tooltip>
              <span style="margin-left: 5px; cursor: pointer;">频度升级阈值</span>
            </template>
            <el-input v-model="form.upgradesCount" min="0" type="number" @change="handleUpgradesCount"
                      style="width: 340px;"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="认证密码" prop="token">
            <template #label>
              <span class="custom-label">
                <span style="color: red;">*</span>
                认证密码
              </span>
            </template>
            <el-input v-model="form.token" @change="handleDraft" clearable placeholder="Client端的和Server端建立连接时的安全认证"
                      style="width: 340px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="form.disenabled" @change="handleDraft">
              <el-radio v-for="dict in disenabledOptions" :key="dict.value" :label="dict.value">{{ dict.label
                }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="templateId">
            <template #label>
              <el-tooltip content="告警模板可在[模板管理]中进行配置" placement="top">
                <i class="el-icon-question" style="margin-left: 5px; color: #E6A23C; cursor: pointer;"></i>
              </el-tooltip>
              <span @click="handleTemplateLabel" class="custom-label" style="color: #1890ff; cursor: pointer;">
                <span style="color: red;">*</span>告警模板</span>
            </template>
            <el-select v-model="form.templateId" filterable clearable @change="handleTemplate" placeholder="请选择告警模板,可在模板配置模块中维护"
                       style="width: 340px;">
              <el-option v-for="template in templateOptions" :key="template.id" :label="template.templateName"
                         :value="template.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="outerWebhookId">
            <template #label>
              <el-tooltip content="外部推送可在[webhook]中进行配置" placement="top">
                <i class="el-icon-question" style="margin-left: 5px; color: #E6A23C; cursor: pointer;"></i>
              </el-tooltip>
              <span @click="handleWebhookLabel"  class="custom-label" style="color: #1890ff; cursor: pointer;">
                <span style="color: red;">*</span>外部推送</span>
            </template>
            <el-select v-model="form.outerWebhookId" @change="handleDraft" filterable clearable placeholder="请选择外部推送,可在webhook模块中维护"
                       style="width: 340px;">
              <el-option v-for="dict in webhookOptions" :key="dict.value" :label="dict.label"
                         :value="dict.value"></el-option>
            </el-select>

          </el-form-item>

        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-divider>告警模板预览</el-divider>
          <el-table :data="templateTableData" empty-text="选择告警模板后可预览模板信息" style="width:100%" height="220" border>
            <el-table-column prop="sort" label="排序" width="80" fixed>
              <template slot-scope="scope">
                <el-tag size="medium">{{ scope.row.sort }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="fieldKey" label="字段名" show-overflow-tooltip width="390">
            </el-table-column>
            <el-table-column prop="fieldValue" label="字段值" show-overflow-tooltip width="478">
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">{{submitButtonText}}</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {groupList, userList, webhookList, addService, updateService} from "@/api/hawkeye/service";
  import {templateList} from "@/api/hawkeye/template";

  export default {
    name: "ServiceModalForm",
    props: {},
    data() {
      return {
        title: "服务告警配置",
        visible: false,
        form: {
          upgradesCount: 3,
          groupId: 1
        },
        groupOptions: [],
        userOptions: [],
        templateOptions: [],
        webhookOptions: [],
        disenabledOptions: [
          {
            label: "启用",
            value: 0
          }, {
            label: "停用",
            value: 1
          }
        ],
        defaultDenoiseRule: {
          denoisePeriod: 0,
          denoiseCount: 0,
          denoiseSilencePeriod: 0
        },
        defaultupgradesCount: 0,
        templateTableData: [],
        submitButtonText: '保存为草稿',
        isDraft: false,
        rules: {
          serviceCnName: [
            {required: true, message: "服务中文名称不能为空", trigger: "blur"}
          ],
          serviceZnName: [
            {required: true, message: "服务英文名不能为空", trigger: "blur"}
          ],
          groupId: [
            {required: true, message: "请选择所属分组", trigger: "change"}
          ]
        }
      };
    },
    created() {
      if (this.checkPermi(['hawk-eye:service-config:query'])) {
        this.getGroupList();
        this.getUpgradesRule();
        this.getDenoiseRule();
        this.getUserList();
      }
      if (this.checkPermi(['hawk-eye:template:query'])) {
        this.getTemplateList();
      }
      if (this.checkPermi(['hawk-eye:webhook:query'])) {
        this.getWebhookList();
      }
    },
    methods: {
      getTemplateList() {
        templateList().then(res => {
          this.templateOptions = res.data;
        })
      },
      getGroupList() {
        groupList().then(res => {
          this.groupOptions = res.data;
        })
      },
      getUpgradesRule() {
        this.defaultupgradesCount = 3;
      },
      getDenoiseRule() {
        this.defaultDenoiseRule.denoisePeriod = 10;
        this.defaultDenoiseRule.denoiseCount = 2;
        this.defaultDenoiseRule.denoiseSilencePeriod = 10;
      },
      getWebhookList() {
        webhookList().then(res => {
          Array.from(res.data).forEach(item => {
            this.webhookOptions.push({"label": item.name, "value": item.id})
          })
        })
      },
      getUserList() {
        userList().then(res => {
          this.userOptions = res.data;
        })
      },
      handleDraft() {
        if (this.form) {
          let token = this.form.token;
          let chargeUserId = this.form.chargeUserId;
          let templateId = this.form.templateId;
          let outerWebhookId = this.form.outerWebhookId;
          if (!token || !chargeUserId || !templateId || !outerWebhookId) {
            this.isDraft = true;
            this.submitButtonText = "保存为草稿";
          } else {
            this.isDraft = false;
            this.submitButtonText = "确 定";
          }
        }
      },
      open(form) {
        this.reset();
        if (form && form.id !== undefined) {
          this.form = form;
          let denoiseRuleObject = JSON.parse(form.denoiseRule)
          this.$set(this.form, "denoisePeriod", denoiseRuleObject.denoisePeriod);
          this.$set(this.form, "denoiseCount", denoiseRuleObject.denoiseCount);
          this.$set(this.form, "denoiseSilencePeriod", denoiseRuleObject.denoiseSilencePeriod);
          this.$set(this.form, "disenabled", form.disenabled);
          this.handleTemplate(form.templateId);
        } else {
          this.$set(this.form, "groupId", '0');
          this.$set(this.form, "disenabled", 0);
          this.$set(this.form, "denoisePeriod", this.defaultDenoiseRule.denoisePeriod);
          this.$set(this.form, "denoiseCount", this.defaultDenoiseRule.denoiseCount);
          this.$set(this.form, "denoiseSilencePeriod", this.defaultDenoiseRule.denoiseSilencePeriod);
          this.$set(this.form, "upgradesCount", this.defaultupgradesCount);
          this.$set(this.form, "isDraft", true);
        }
        this.handleDraft();
        this.visible = true;
      },
      cancel() {
        this.visible = false;
        this.reset();
        this.$emit("cancel");
      },
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(this.isDraft === true){

            }
            this.form["denoiseRule"] = JSON.stringify({
              "denoisePeriod": this.form.denoisePeriod,
              "denoiseCount": this.form.denoiseCount,
              "denoiseSilencePeriod": this.form.denoiseSilencePeriod
            })
            this.$set(this.form, 'isDraft', this.isDraft === true ? 1 : 0)
            if (this.form.id != undefined) {
              updateService(this.form).then(res => {
                this.$modal.msgSuccess("修改成功");
                this.visible = false;
                this.$emit("submitted", res);
              });
            } else {
              addService(this.form).then(res => {
                this.$modal.msgSuccess(this.isDraft === true ? "已保存为草稿" : "新增成功");
                this.visible = false;
                this.$emit("submitted", res);
              });
            }
          }
        });
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {};
        this.templateTableData = [];
        this.resetForm("form");
      },
      handleTemplateLabel() {
        this.$router.push('/hawkeye/template')
      },
      handleWebhookLabel() {
        this.$router.push('/hawkeye/webhook')
      },
      handleUpgradesCount() {
        if (this.form.upgradesCount <= 0) {
          this.$modal.msgWarning("升级阈值最小可设置为0,表示不进行升级,默认一级");
          this.$set(this.form, 'upgradesCount', 0);
        }
      },
      handleDenoisePeriod() {
        if (this.form.denoisePeriod <= 0) {
          this.$modal.msgWarning("周期最小可设置为0,表示不降噪");
          this.$set(this.form, 'denoisePeriod', 0);
          this.$set(this.form, 'denoiseCount', 0);
          this.$set(this.form, 'denoiseSilencePeriod', 0);
        }
      },
      handleTemplate(id) {
        this.templateTableData = [];
        if (!id) {
          return;
        }
        Array.from(this.templateOptions).forEach(e => {
          if (e.id == id) {
            this.templateTableData = e.templateNodes;
          }
        });
      },
      addTemplateAttr() {
        let length = this.templateTableData.length;
        this.templateTableData.push(
          {
            id: null,
            key: '',
            value: '',
            sort: length + 1,
          })
      },
    }
  };
</script>
<style scoped="css">
  .custom-label {
    /* 调整星号位置 */
    margin-right: 4px;
  }
</style>
